package org.qh.web.license;

import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.qh.common.core.constant.Environment;
import org.qh.common.core.exception.BusinessException;
import org.qh.common.core.utils.SpringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 在项目启动时安装证书
 */
@Component
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(LicenseCheckListener.class);

    @Resource
    private LicenseVerifyParam licenseProperties;

    @Override
    public void onApplicationEvent(@NotNull ContextRefreshedEvent event) {
        if (Objects.equals(SpringUtils.getActiveProfile(), Environment.TEST)
            || Objects.equals(SpringUtils.getActiveProfile(), Environment.DEV)){
            return;
        }
        ApplicationContext context = event.getApplicationContext().getParent();
        if (context == null) {
            try {
                String licensePath = licenseProperties.getLicensePath();
                if (StringUtils.isNotBlank(licensePath)) {
                    logger.info("--------------- 开始安装证书 ---------------");

                    LicenseVerifyParam param = new LicenseVerifyParam();
                    param.setSubject(licenseProperties.getSubject());
                    param.setPublicAlias(licenseProperties.getPublicAlias());
                    param.setStorePass(licenseProperties.getStorePass());
                    param.setLicensePath(licensePath);
                    param.setPublicKeysStorePath(licenseProperties.getPublicKeysStorePath());

                    LicenseVerify licenseVerify = new LicenseVerify();
                    //安装证书
                    licenseVerify.install(param);
                } else {
                    // 终止服务
                    throw new BusinessException("获取license路径失败，请检查配置文件中的license.licensePath属性");
                }
            } catch (Exception e) {
                // 终止服务
                throw new BusinessException("证书安装失败, 请配置正确的License证书");
            }
        }
    }
}
